package threadSafe;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * @author： pang-yun
 * @date： 2021-10-19 09:49
 * 功能目的 ：用于 转账
 */

@Slf4j
public class ExceciseTransfer {

    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAccount());
            }
        }, "pang");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAccount());
            }
        }, "xiaoyang");

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        log.info("total: {}", a.getMoney() + b.getMoney());
    }

    //线程安全
    static Random random = new Random();

    //随机 1-100
    public static int randomAccount() {
        return random.nextInt(100) + 1;
    }
}



// 账户
  class  Account {
    private int money;

    public Account(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    // 转账
    public void transfer(Account target, int account) {
        synchronized (this) {
            if (this.money >= account) {
                this.setMoney(this.getMoney() - account);
                target.setMoney(target.getMoney() + account);
            }
        }
    }
}
